<template>
  <cs-card>
    <el-table
      v-loading="isLoading"
      ref="multipleTable"
      :data="tableData"
      tooltip-effect="dark"
      style="width: 100%"
      :header-cell-style="{ 'text-align': 'center' }"
      :cell-style="{ 'text-align': 'center' }"
      @selection-change="selectionChange"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="id" label="站点编码" width="180"> </el-table-column>
      <el-table-column prop="name" label="站点名称" width="100"> </el-table-column>
      <el-table-column prop="companyName" label="所属企业"> </el-table-column>
      <el-table-column label="站点类型" width="150"> 货场 </el-table-column>
      <el-table-column prop="location" label="位置"> </el-table-column>
      <el-table-column label="检测方向" width="150"> 出场 </el-table-column>
      <el-table-column prop="laneNum" label="车道数量" width="120">
        <template v-slot="scoped">
          {{ scoped.row.laneNum ? scoped.row.laneNum : '—' }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150" fixed="right">
        <template v-slot="scoped">
          <el-link type="primary" class="details" @click="detailSiteDialogVisible(scoped.row.id)"
            >详情</el-link
          >
          <el-link v-if="innerMenu.upd.flag" type="primary" class="details" @click="alterSiteDialogVisible(scoped.row)"
            >编辑</el-link
          >
          <el-link v-if="innerMenu.del.flag" type="primary" @click="deleteSiteDialogVisible('multipleTable', scoped.row.id)"
            >删除</el-link
          >
        </template>
      </el-table-column>
    </el-table>
    <div id="pagination_section">
      <span class="currentSelect">{{ `已选${currentSelect}项，共${totalCount}项` }}</span>
      <div class="pagination_right">
        <span>{{ `${pageSize}条/页` }}</span>
        <cs-pagination
          :currentPage="currentPage"
          :totalPage="totalPage"
          @firstPageClick="firstPageClick"
          @previousPageClick="previousPageClick"
          @nextPageClick="nextPageClick"
          @lastPageClick="lastPageClick"
          @junkToOtherPage="junkToOtherPage"
        />
      </div>
    </div>
  </cs-card>
</template>

<script>
import csCard from '@/components/cs-card/cs-card.vue'
import csPagination from '@/components/cs-pagination/cs-pagination.vue'
import { getSiteInfo, exportlistsite } from '@/service/operate/site_manage/site_manage'

export default {
  components: {
    csCard,
    csPagination
  },
  props: {
    innerMenu: {
      require: true,
      type: Object
    }
  },
  data() {
    return {
      tableData: [],
      // 当前页码
      currentPage: 1,
      // 一页的条数
      pageSize: 10,
      // 总共多少条数据
      totalCount: 0,
      // 总共多少页
      totalPage: 0,
      currentSelect: 0,
      selectId: [],
      siteName: '',
      siteId: '',
      siteType: '',
      isLoading: true
    }
  },
  created() {
    this.getSiteInfo()
    // 发送表格选中的表格项
    this.$bus.$emit('siteSelectNum', this.currentSelect)
    // 当添加站点成功后，刷新表格
    this.$bus.$on('addSiteSuccess', () => {
      this.getSiteInfo(this.currentPage)
    })
    // 当修改站点成功后，刷新表格
    this.$bus.$on('alterSiteSuccess', () => {
      this.getSiteInfo(this.currentPage)
      console.log('aaa')
    })
    // 当删除站点成功后，刷新表格
    this.$bus.$on('delSiteSuccess', () => {
      this.getSiteInfo()
    })
    // 当点击搜索按钮时，刷新表格
    this.$bus.$on('siteSearchBtnClick', (res) => {
      if (this.isLoading) return
      const { siteName, siteNumber } = res
      this.siteName = siteName
      this.siteId = siteNumber
      // this.siteType = siteTypeValue
      this.getSiteInfo(1, 10)
    })
    this.$bus.$on('site_exportlist', (res) => {
      this.exportfn(res)
    })
  },
  beforeDestroy() {
    console.log('表格关闭')
    this.$bus.$off('site_exportlist')
    this.$bus.$off('siteSelectNum')
    this.$bus.$off('detailSiteDialogVisible')
    this.$bus.$off('alterSiteDialogVisible')
    this.$bus.$off('deleteSiteDialogVisible')
    this.$bus.$off('siteSelectNum')
    this.$bus.$off('siteSelectId')
    // this.$bus.$off('alterSiteSuccess')
  },
  methods: {
    detailSiteDialogVisible(id) {
      this.$bus.$emit('detailSiteDialogVisible', id)
    },
    alterSiteDialogVisible(row) {
      this.$bus.$emit('alterSiteDialogVisible', row)
    },
    deleteSiteDialogVisible(formName, delId) {
      this.$refs[formName].clearSelection()
      this.$bus.$emit('deleteSiteDialogVisible', [delId], 1)
    },
    // 获取表格数据
    async getSiteInfo(
      pageNum = 1,
      pageSize = 10,
      name = this.siteName,
      id = this.siteId,
      type = this.siteType
    ) {
      try {
        this.isLoading = true
        this.tableData = []
        const { code,data } = await getSiteInfo(pageNum, pageSize, name, id, type)

        const siteTableData = data
        if (code === 0) {
          siteTableData.list.forEach((item) => {
            // 拼接表格数据
            this.tableData.push({ ...item })
          })
          // 当前页码
          this.currentPage = siteTableData.currPage - 0
          // 一页的条数
          this.pageSize = siteTableData.pageSize
          this.totalCount = siteTableData.totalCount
          this.totalPage = siteTableData.totalPage - 0
          this.isLoading = false
        }
      } catch (err) {
        console.log(err)
        this.$message.error('服务器出错了')
      }
    },
    // 表格选择项变化时触发事件
    selectionChange(selection) {
      this.selectId = []
      // 获取当前选择多少项
      this.currentSelect = selection.length
      this.$bus.$emit('siteSelectNum', this.currentSelect)
      selection.forEach((item) => {
        this.selectId.push(item.id)
      })
      this.$bus.$emit('siteSelectId', this.selectId)
    },
    async exportfn(info) {
      const loading = this.$loading({
        lock: true,
        text: '下载中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      const data = await exportlistsite(info)
      console.log('导出表格数据', data)
      if (!!data) {
        const filename = '站点信息表.xlsx'
        const blob = new Blob([data], { type: 'application/vnd.ms-excel' })
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          // 兼容IE，window.navigator.msSaveBlob：以本地方式保存文件
          window.navigator.msSaveBlob(blob, decodeURI(filename))
        } else {
          // 创建新的URL并指向File对象或者Blob对象的地址
          const blobURL = window.URL.createObjectURL(blob)
          // 创建a标签，用于跳转至下载链接
          const tempLink = document.createElement('a')
          tempLink.style.display = 'none'
          tempLink.href = blobURL
          tempLink.setAttribute('download', decodeURI(filename))
          // 兼容：某些浏览器不支持HTML5的download属性
          if (typeof tempLink.download === 'undefined') {
            tempLink.setAttribute('target', '_blank')
          }
          // 挂载a标签
          document.body.appendChild(tempLink)
          tempLink.click()
          document.body.removeChild(tempLink)
          // 释放blob URL地址
          window.URL.revokeObjectURL(blobURL)
        }
        setTimeout(() => {
          loading.close()
        }, 2000)
      } else {
        setTimeout(() => {
          loading.close()
        }, 2000)
      }
    },
    // 第一页
    firstPageClick() {
      if (this.isLoading) return
      this.getSiteInfo(1)
    },
    // 上一页
    previousPageClick() {
      if (this.isLoading) return
      this.getSiteInfo(this.currentPage - 1)
    },
    // 下一页
    nextPageClick() {
      if (this.isLoading) return
      this.getSiteInfo(this.currentPage + 1)
    },
    // 最后一页
    lastPageClick() {
      if (this.isLoading) return
      this.getSiteInfo(this.totalPage)
    },
    // 跳转页
    junkToOtherPage(page) {
      this.getSiteInfo(page, this.pageSize)
    }
  }
}
</script>

<style scoped>
.el-form-item >>> .el-form-item__label {
  color: #888888;
}

/* 表格选择框样式start */
.el-table >>> .el-checkbox__inner {
  width: 20px;
  height: 20px;
}

.el-table >>> .el-checkbox__inner::after {
  top: 3px;
  left: 6px;
}

.el-table >>> .el-checkbox__inner::before {
  top: 8px;
}
/* 表格选择框样式end */

.el-select >>> .el-input__inner {
  border-radius: 0;
}

.el-input >>> .el-input__inner {
  border-radius: 0;
}

.form-select {
  width: 100%;
}
</style>
